<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { apiGet } from '../../utils/api.js'

const router = useRouter()

// 仪表板数据
const dashboardData = ref({
  totalProducts: 0,
  totalCategories: 0,
  monthlyAdded: 0,
  monthlyUpdated: 0
})

// 最近活动数据
const recentActivities = ref([])

// 加载仪表板数据
async function loadDashboardData() {
  try {
    const res = await apiGet('/commodity/dashboard')
    const payload = (res && typeof res === 'object' && 'data' in res && res.data) ? res.data : res
    if (payload && typeof payload === 'object') {
      dashboardData.value = {
        totalProducts: Number(payload.totalProducts) || 0,
        totalCategories: Number(payload.totalCategories) || 0,
        monthlyAdded: Number(payload.monthlyAdded) || 0,
        monthlyUpdated: Number(payload.monthlyUpdated) || 0
      }
    }
  } catch (error) {
    console.error('加载商品仪表板数据失败:', error)
    // 使用默认数据
    dashboardData.value = {
      totalProducts: 1250,
      totalCategories: 45,
      monthlyAdded: 156,
      monthlyUpdated: 89
    }
  }
}

// 加载最近活动
async function loadRecentActivities() {
  try {
    // 并发拉取：商品档案、商品分类
    const [products, categories] = await Promise.all([
      apiGet('/commodity/products').catch(() => ({ items: [] })),
      apiGet('/commodity/categories').catch(() => ({ items: [] }))
    ])

    const normalize = (res) => {
      const payload = res && typeof res === 'object' && 'data' in res ? res.data : res
      if (Array.isArray(payload)) return payload
      if (payload && Array.isArray(payload.items)) return payload.items
      if (payload && Array.isArray(payload.list)) return payload.list
      if (payload && Array.isArray(payload.records)) return payload.records
      if (payload && Array.isArray(payload.rows)) return payload.rows
      if (payload && Array.isArray(payload.content)) return payload.content
      return []
    }

    const productActivities = normalize(products).map((r) => ({
      id: `prod_${r.id}`,
      type: 'product',
      icon: '📦',
      title: '商品更新',
      description: `${r.name || '商品'} ${r.sku || ''} 已更新`,
      time: r.updateTime || r.createTime || ''
    }))

    const categoryActivities = normalize(categories).map((r) => ({
      id: `cat_${r.id}`,
      type: 'category',
      icon: '📁',
      title: '分类更新',
      description: `分类 ${r.name || '未命名'} 已更新`,
      time: r.updateTime || r.createTime || ''
    }))

    // 合并并按时间倒序，取最近6条
    const all = [...productActivities, ...categoryActivities].filter(a => a && (a.title || a.description))
    const parseTime = (t) => new Date(t || 0).getTime() || 0
    recentActivities.value = all.sort((a, b) => parseTime(b.time) - parseTime(a.time)).slice(0, 6)
  } catch (error) {
    console.error('加载商品最近活动失败:', error)
    recentActivities.value = []
  }
}

// 格式化数字
function formatNumber(num) {
  return new Intl.NumberFormat('zh-CN').format(num || 0)
}

// 页面加载时获取数据
onMounted(() => {
  loadDashboardData()
  loadRecentActivities()
})
</script>

<template>
  <div class="commodity-dashboard">
    <div class="dashboard-header">
      <h1>商品管理</h1>
      <p class="subtitle">商品档案管理与分类维护</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon product-icon">📦</div>
        <div class="stat-content">
          <h3>商品总数</h3>
          <p class="stat-value">{{ formatNumber(dashboardData.totalProducts) }}</p>
          <p class="stat-subtitle">本月新增: {{ formatNumber(dashboardData.monthlyAdded) }}</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon category-icon">📁</div>
        <div class="stat-content">
          <h3>商品分类</h3>
          <p class="stat-value">{{ formatNumber(dashboardData.totalCategories) }}</p>
          <p class="stat-subtitle">分类管理</p>
        </div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <h2>快捷操作</h2>
      <div class="action-buttons">
        <div class="action-card product-card" @click="router.push('/commodity/list')">
          <div class="card-background">
            <div class="card-pattern"></div>
          </div>
          <div class="card-content">
            <div class="card-icon">
              <div class="icon-wrapper">
                📋
              </div>
            </div>
            <div class="card-text">
              <h3>商品档案</h3>
              <p>管理商品基本信息、规格参数、价格等详细资料</p>
              <div class="card-stats">
                <span class="stat-item">
                  <span class="stat-number">{{ formatNumber(dashboardData.totalProducts) }}</span>
                  <span class="stat-label">商品总数</span>
                </span>
                <span class="stat-item">
                  <span class="stat-number">{{ formatNumber(dashboardData.monthlyAdded) }}</span>
                  <span class="stat-label">本月新增</span>
                </span>
              </div>
            </div>
            <div class="card-arrow">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
          </div>
        </div>
        
        <div class="action-card category-card" @click="router.push('/commodity/category')">
          <div class="card-background">
            <div class="card-pattern"></div>
          </div>
          <div class="card-content">
            <div class="card-icon">
              <div class="icon-wrapper">
                📁
              </div>
            </div>
            <div class="card-text">
              <h3>商品分类</h3>
              <p>建立商品分类体系，便于商品管理和查找</p>
              <div class="card-stats">
                <span class="stat-item">
                  <span class="stat-number">{{ formatNumber(dashboardData.totalCategories) }}</span>
                  <span class="stat-label">分类总数</span>
                </span>
                <span class="stat-item">
                  <span class="stat-number">{{ formatNumber(dashboardData.monthlyUpdated) }}</span>
                  <span class="stat-label">本月更新</span>
                </span>
              </div>
            </div>
            <div class="card-arrow">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activities">
      <h2>最近活动</h2>
      <div class="activity-list">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
          <div class="activity-icon" :class="activity.type">{{ activity.icon }}</div>
          <div class="activity-content">
            <h4>{{ activity.title }}</h4>
            <p>{{ activity.description }}</p>
            <span class="activity-time">{{ activity.time }}</span>
          </div>
        </div>
        <div v-if="recentActivities.length === 0" class="no-activities">
          <div class="empty-icon">📝</div>
          <p>暂无最近活动</p>
          <span class="empty-hint">开始使用商品管理功能后，这里将显示最近的操作记录</span>
        </div>
      </div>
    </div>

    <!-- 使用提示 -->
    <div class="usage-tips">
      <h2>使用提示</h2>
      <div class="tips-grid">
        <div class="tip-card">
          <div class="tip-icon">💡</div>
          <div class="tip-content">
            <h4>商品档案管理</h4>
            <p>建议先建立商品分类体系，再录入商品信息，这样可以提高管理效率。</p>
          </div>
        </div>
        
        <div class="tip-card">
          <div class="tip-icon">⚡</div>
          <div class="tip-content">
            <h4>快速操作</h4>
            <p>使用快捷操作按钮可以快速访问常用功能，提高工作效率。</p>
          </div>
        </div>
        
        <div class="tip-card">
          <div class="tip-icon">📊</div>
          <div class="tip-content">
            <h4>数据统计</h4>
            <p>定期查看统计信息，了解商品管理情况，及时调整管理策略。</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.commodity-dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
}

.dashboard-header h1 {
  color: #1f2937;
  margin-bottom: 8px;
}

.subtitle {
  color: #6b7280;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  font-size: 32px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
}

.product-icon { background: #dbeafe; }
.category-icon { background: #fef3c7; }

.stat-content h3 {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 14px;
  font-weight: 500;
}

.stat-value {
  margin: 0 0 4px 0;
  color: #111827;
  font-size: 24px;
  font-weight: 700;
}

.stat-subtitle {
  margin: 0;
  color: #6b7280;
  font-size: 12px;
}

.quick-actions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 30px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.quick-actions h2 {
  margin: 0 0 20px 0;
  color: #1f2937;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
}

.action-card {
  position: relative;
  height: 200px;
  border-radius: 16px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.action-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.category-card .card-background {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
}

.card-content {
  position: relative;
  z-index: 2;
  height: 100%;
  padding: 24px;
  display: flex;
  flex-direction: column;
  color: white;
}

.card-icon {
  margin-bottom: 16px;
}

.icon-wrapper {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.card-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.card-text h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
}

.card-text p {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.4;
}

.card-stats {
  display: flex;
  gap: 20px;
  margin-top: auto;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255, 255, 255, 0.15);
  padding: 8px 12px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.stat-number {
  font-size: 18px;
  font-weight: 700;
  color: white;
}

.stat-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 2px;
}

.card-arrow {
  position: absolute;
  top: 24px;
  right: 24px;
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.action-card:hover .card-arrow {
  transform: translateX(4px);
  background: rgba(255, 255, 255, 0.3);
}

.card-arrow svg {
  width: 16px;
  height: 16px;
  color: white;
}

.recent-activities {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.recent-activities h2 {
  margin: 0 0 20px 0;
  color: #1f2937;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 16px;
  border-radius: 8px;
  background: #f9fafb;
  transition: background 0.2s;
}

.activity-item:hover {
  background: #f3f4f6;
}

.activity-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-size: 20px;
}

.activity-icon.product { background: #dbeafe; }
.activity-icon.category { background: #fef3c7; }

.activity-content h4 {
  margin: 0 0 4px 0;
  color: #111827;
  font-size: 14px;
  font-weight: 600;
}

.activity-content p {
  margin: 0 0 4px 0;
  color: #6b7280;
  font-size: 13px;
}

.activity-time {
  color: #9ca3af;
  font-size: 12px;
}

.no-activities {
  text-align: center;
  padding: 40px;
  color: #6b7280;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-hint {
  display: block;
  margin-top: 8px;
  font-size: 12px;
  color: #9ca3af;
}


/* 使用提示 */
.usage-tips {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.usage-tips h2 {
  margin: 0 0 20px 0;
  color: #1f2937;
}

.tips-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.tip-card {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #bae6fd;
  transition: all 0.3s ease;
}

.tip-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.tip-icon {
  font-size: 24px;
  margin-bottom: 12px;
}

.tip-content h4 {
  margin: 0 0 8px 0;
  color: #1e40af;
  font-size: 16px;
  font-weight: 600;
}

.tip-content p {
  margin: 0;
  color: #1e3a8a;
  font-size: 14px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .commodity-dashboard {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
  }
  
  .action-card {
    height: 180px;
  }
  
  .card-content {
    padding: 20px;
  }
  
  .icon-wrapper {
    width: 50px;
    height: 50px;
    font-size: 24px;
  }
  
  .card-text h3 {
    font-size: 18px;
  }
  
  .card-text p {
    font-size: 13px;
  }
  
  .card-stats {
    gap: 16px;
  }
  
  .stat-item {
    padding: 6px 10px;
  }
  
  .stat-number {
    font-size: 16px;
  }
  
  .tips-grid {
    grid-template-columns: 1fr;
  }
}
</style>


